import Demo1.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet({"/ajax3Request"})
public class ajax3Request extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        // 重写post方法,前端发送post请求
        // 获取用户名
        String username = req.getParameter("username");

        // 连接数据库
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        // 获取连接
        connection =DBUtil.getConnection();
        // 执行sql语句

        String sql = "select username from t_username where username = ?";

        try {
            // 从数据库中查询
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            resultSet = preparedStatement.executeQuery();
             if(resultSet.next()){
                 out.print("<font color='green'>用户名可以使用<font/>");
             }else{
                 out.print("<font color='red'>对不起,该用户名不存在<font/>");
             }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }
}
